<template>
  <ActionPanel :loading="loading">
    <div v-if="id && detail">
      <el-descriptions v-if="detail" :title="`${seed?.label}基本信息`" border :column="2" class="mb-10px">
        <el-descriptions-item v-for="(column, i) in cross.columns" :label="column.label" :key="i">
          <component :is="getElement(column.type, 'read', action.elements?.[column.name]?.element)"
            v-model="detail[toCamelCase(column.name)]" :action="action" :column="column"
            v-bind="action.elements?.[column.name]?.elementProps" />
        </el-descriptions-item>
      </el-descriptions>
      <template v-for="(relation, cross) in cross.crosses">
        <DetailList v-if="relation.type == 'hasMany' || relation.type == 'habtm'" :many="relation" :data="detail[cross]" />
        <Detail v-else :action="action" :one="relation" :data="detail[cross]" :column="2" />
      </template>
    </div>
    <ElEmpty v-else description="数据不存在" class="full" />
    <template v-if="close" #footer>
      <el-button @click="close">关闭</el-button>
    </template>
  </ActionPanel>
</template>
<script setup lang="ts">
  import { ElButton, ElDescriptions, ElDescriptionsItem, ElEmpty } from 'element-plus'
  import { closePopupKey } from '@/components/Popup'
  import { buildDeclared, getCross, getDeclares } from '@/seed-application/utils/SeedUtil'
  import { Detail, DetailList } from '@/components/crud'
  import { toCamelCase } from '@/utils/func'
  import { ActionPanel } from '@/components/ActionPanel'
  import { inject, onMounted, ref } from 'vue'
  import { detailApi } from '@/seed-application/api'
  import { getAction, getElement } from '@/seed-application'

  export type PropsType = { actionName: string, seedName?: string, microName?: string, id: string }
  const props = defineProps<PropsType>()
  const action = getAction(props.actionName, props.seedName, props.microName)
  const seed = action?.seed

  const declared = buildDeclared(seed, getDeclares(action))
  const cross = getCross(seed, declared)

  const close = inject<() => void>(closePopupKey, void 0)

  const detail = ref()
  console.log('action detail == ', action)
  const loading = ref(false)
  onMounted(async () => {
    if(props.id) {
      try {
        loading.value = true
        detail.value = await detailApi(action, props.id)
      } finally {
        loading.value = false
      }
    }
  })
</script>